import ImageExcel from '@/assets/filetype/excel.png';
import ImageOther from '@/assets/filetype/other.png';
import ImagePdf from '@/assets/filetype/pdf.png';
import ImageTxt from '@/assets/filetype/txt.png';
import ImageWord from '@/assets/filetype/word.png';
import { take_pictures_api } from '@/services/public/gaopaiyi';
import { base64ToStream } from '@/utils/fileStream';
import { beforeInterceptString } from '@/utils/string';
import { timestamp } from '@/utils/timestamp';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { useModel } from '@umijs/max';
import type { UploadProps } from 'antd';
import { Button, Drawer, Image, message, Tooltip, Upload } from 'antd';
import React, { useEffect, useState } from 'react';
import { MyIcon } from '../MyIcon';
import { upload_file_stream_api } from './api/other';
import styles from './index.less';
const Gaopaiyi_Url = 'http://127.0.0.1:38088/video=stream&camidx=0';
export type UploadAnnexProps = {
  isCamera: boolean; //是否启用高拍仪
  label?: string;
  initValue: PublicApi.ResAnnexFile[];
  onChange: (list: PublicApi.ResAnnexFile[]) => void;
  onDelete: (list: PublicApi.ResAnnexFile[]) => void;
};
const UploadMultipleLocal: React.FC<UploadAnnexProps> = (props) => {
  const { isCamera, label, onChange, initValue, onDelete } = props;

  const [btnSaomiao, setBtnSaomiao] = useState(false);
  const [openGaopaiyi, setOpenGaopaiyi] = useState(false);
  const [loading, setLoading] = useState(false);
  const [AnnexList, setAnnexList] = useState<PublicApi.ResAnnexFile[]>([]);
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};

  useEffect(() => {
    if (initValue.length > 0) {
      console.log(initValue);
      setAnnexList(initValue);
    } else {
      setAnnexList([]);
    }
  }, [initValue]);

  const uploadButton = <div>{loading ? <LoadingOutlined /> : <PlusOutlined />}</div>;
  //上传配置 可以上传png,jpg,jpeg,doc,docx,pdf,txt,xls,xlsx
  const fileType =
    'image/png, image/jpeg,application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/pdf, text/plain,application/vnd.ms-excel application/x-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  const propsUpload: UploadProps = {
    name: 'file',
    accept: fileType,
    showUploadList: false,
    maxCount: 1,
    action: '/apiupload/admin/z_file/upload',
    headers: {
      Token: currentUser?.token ?? '',
    },
    beforeUpload(file) {
      setLoading(true);
      if (fileType.indexOf(file.type) !== -1) {
        return true;
      }
      message.error('你所选的文件类型不支持');
      return false;
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        setLoading(false);
      }
      if (info.file.status === 'done') {
        const res = info.file.response;
        if (res.success) {
          const annexItem: PublicApi.ResAnnexFile = {
            ID:res.data.id,
            Name:res.data.originalName,
            AnnexType:res.data.extensionName.substring(1),
            Path:res.data.ramark
          };
          const list: PublicApi.ResAnnexFile[] = AnnexList;
          list.push(annexItem);
          setAnnexList([...list]);
          onChange(list);
          message.success(`${info.file.name} 上传成功`);
        } else {
          message.error(`${info.file.name} 上传失败`);
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
  };
  return (
    <div>
      <div className={styles.title}>
        <span>{label}</span>
      </div>
      <div className={styles.list}>
        {AnnexList.map((item) => {
          let showType = ImageOther;
          if (item.AnnexType === 'doc' || item.AnnexType === 'docx') {
            showType = ImageWord;
          } else if (item.AnnexType === 'pdf') {
            showType = ImagePdf;
          } else if (item.AnnexType === 'txt') {
            showType = ImageTxt;
          } else if (
            item.AnnexType === 'png' ||
            item.AnnexType === 'jpg' ||
            item.AnnexType === 'jpeg'
          ) {
            showType = `${item.Path}`;
          } else if (item.AnnexType === 'xls' || item.AnnexType === 'xlsx') {
            showType = ImageExcel;
          } else {
            showType = ImageOther;
          }

          return (
            <div className={styles.flieItem} key={item.ID}>
              <div className={styles.delete}>
                <MyIcon
                  type="icon-cuowu"
                  style={{ color: '#F56C6C', fontSize: 18 }}
                  onClick={() => {
                    const list: PublicApi.ResAnnexFile[] = AnnexList;
                    const index = list.findIndex((items) => items.ID === item.ID);

                    list.splice(index, 1);
                    setAnnexList([...list]);

                    onDelete(list);
                  }}
                />
              </div>
              <div className={styles.showFile}>
                <img src={showType} alt="" />
                <Tooltip title={item.Name} color="#909399">
                  <span>{beforeInterceptString(item.Name, 5)}</span>
                </Tooltip>
              </div>
            </div>
          );
        })}
        {isCamera ? (
          <div
            className={styles.upload}
            onClick={() => {
              setOpenGaopaiyi(true);
            }}
          >
            {uploadButton}
          </div>
        ) : (
          <Upload {...propsUpload}>
            <div className={styles.upload}>{uploadButton}</div>
          </Upload>
        )}
      </div>
      <Drawer
        title="高拍仪"
        placement="right"
        maskClosable={true}
        onClose={() => {
          setOpenGaopaiyi(false);
        }}
        open={openGaopaiyi}
      >
        <div className={styles.pageGaopaiyi}>
          <Image width={300} placeholder={true} preview={false} src={Gaopaiyi_Url} />
          <div className={styles.btnGaopaiyi}>
            <Button
              loading={btnSaomiao}
              type="primary"
              size="large"
              style={{ width: 300 }}
              onClick={async () => {
                setBtnSaomiao(true);
                const res = await take_pictures_api();
                console.log(res);
                const imagebase64 = `data:image/jpeg;base64,${res.data.photoBase64}`;

                // console.log(imagebase64);
                const filename = `dangan_${timestamp()}`;

                const fileStream = base64ToStream(imagebase64, filename);
                // console.log(fileStream);
                const formData = new FormData();
                formData.append('file', fileStream);
                const resupload = await upload_file_stream_api(formData, currentUser?.token ?? '');
                // console.log(resupload);
                setBtnSaomiao(false);
                if (resupload.data.success) {
                  const annexItem: PublicApi.ResAnnexFile = resupload.data.data;
                  const list: PublicApi.ResAnnexFile[] = AnnexList;
                  list.push(annexItem);
                  setAnnexList([...list]);
                  onChange(list);
                  message.success(`扫描成功`);
                } else {
                  message.error(`扫描失败`);
                }
              }}
            >
              扫描
            </Button>
          </div>
        </div>
      </Drawer>
    </div>
  );
};
//整体提交业务数据库
export default UploadMultipleLocal;
